package com.gogant.spider.util;

public class CharsetUtils {
	private static ThreadLocal<Object> detectorLocal = new ThreadLocal<Object>();

	public static String detectCharset(byte[] bytes, int offset, int length) {
		Object object = detectorLocal.get();
		try {
			if (object == null) {
				object = new org.mozilla.universalchardet.UniversalDetector(null);
				detectorLocal.set(object);
			}
		} catch (Throwable e) {
			return null;
		}
		org.mozilla.universalchardet.UniversalDetector detector = (org.mozilla.universalchardet.UniversalDetector) object;
		try {
			detector.handleData(bytes, offset, length);
			detector.dataEnd();
			String charsetName = detector.getDetectedCharset();
			return charsetName;
		} finally {
			detector.reset();
		}

	}
}
